<?php
namespace App\Jobs\goods;

use App\Models\config\Config;
use App\Models\goods\Order;
use App\Models\log\ErrorLog;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Cache;
use App\Api\PrintService;
use App\Config\YlyConfig;
use App\Oauth\YlyOauthClient;

class PrintTicket implements ShouldQueue
{


    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    protected $order;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct( Order $order)
    {
        $this->order = $order;
    }

    /**
     *
     * 产品浏览次数叠加
     *
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {



        // pw 80 可打印48个字符  中文占2字符
//        dd(strlen('*'),strlen(' '),strlen('A'),strlen('a'),strlen('小'),strlen(8),strlen(')'));
        $all = 48;
        $order = $this->order;
        try{
            $config = new YlyConfig(\config('yly.clientId'),\config('yly.clientSecret'));

            if (Cache::has('ylyToken')){
                $token = Cache::get('ylyToken');
            }else{
                $client = new YlyOauthClient($config);
                $token = $client->getToken();   //若是开放型应用请传授权码code
                Cache::put('ylyToken',$token,Carbon::now()->addDay());
            }

            $print = new PrintService($token->access_token, $config);

            $content = "<PW>080</PW>\n".str_repeat(' ', 14)."<FS2>**牛视界**</FS2>\n";
            $content .= str_repeat('*', 22) . "商品" . str_repeat("*", 22)."\n";
//            $content .= "<table>";
//            $content .= "<tr><td>商品名</td><td>规格</td><td>数量</td><td>价格</td></tr>";

            $content.= sprintf("商品名%s规格%s数量%s价格\n",str_repeat(' ', 16),str_repeat(' ', 6),str_repeat(' ', 4),str_repeat(' ', 2));

            // 名称  占位24  间隔2   规格占位14  间隔2  数量占位6  间隔2  价格占位6  间隔2
            $name_max = 23;
            $spec_max = 10;
            $num_max  = 4;
            $price_max = 4;
            foreach ($order->details as $detail){

                if (!empty($detail->goods_alias)){
                    $name = $detail->goods_alias;
                }else{
                    $name = $detail->goods_name;
                }
//                $name = $detail->goods_name;
                if ($detail->type_name){
                    $name .= '('.$detail->type_name.')';
                }
                $goods_name_count = $this->getWordsCount($name);
                if ($name_max > $goods_name_count){
                    $n = $name_max-$goods_name_count-1;
//                    if ($n % 2 == 1){
//                        $n --;
//                    }
                    $content.= $name.str_repeat(' ', $n);
                }else{
                    $content.= $name.str_repeat(' ', 2);
                }

                $spec = '';
                if (!empty($detail->spec_alias)){
                    $spec = $detail->spec_alias;
                }else if (!empty($detail->spec)){
                    $spec = $detail->spec;
                }

//                $spec = $detail->spec;
                $spec_count = $this->getWordsCount($spec);
                if ($spec_max > $spec_count){
                    $n = $spec_max-$spec_count;
                    if ($n % 2 == 1){
                        $n ++;
                    }
                    $content.= $spec.str_repeat(' ', $n);
                }else{
                    $content.= $spec.str_repeat(' ', 2);
                }

                if ($num_max > strlen($detail->num)){
                    $n = $num_max-strlen($detail->num)+2;
                    if ($n % 2 == 1){
                        $n ++;
                    }
                    $content.= $detail->num.str_repeat(' ',$n );
                }else{
                    $content.= $detail->num.str_repeat(' ', 2);
                }

                if ($price_max > strlen($detail->total_price)){
                    $content.= $detail->total_price.str_repeat(' ', $price_max-strlen($detail->total_price)+2);
                }else{
                    $content.= $detail->total_price.str_repeat(' ', 2);
                }
                $content.="\n";
            }

//            $content .= "</table>";

//            $content .= "小计:￥".$order->old_price."\n";

//            $content .= "折扣:￥".($order->old_price - $order->total_price)." \n";
            $content .= str_repeat('*', 48)."\n";
            $content .= "订单总价:￥".$order->total_price." \n";

//        $content .= "<FS><center>张周兄弟烧烤</center></FS>";
            $content .= "收件人:".$order->user_name."\n";
            $content .= "联系电话:".$order->phone."\n";
            $content .= "收件地址:".$order->detail."\n";
            $content .= "订单编号:".$order->order_no."\n";
            $content .= "订单时间:". $order->pay_at . "\n";
            $content .= "牛视界客服:". Config::getConfig('phone'). "\n";

            $content .= str_repeat('.', 48)."\n";
            $content .= sprintf("<QR>custom=/v1/orders/signFor=%d</QR>",$order->id);

            if ($order->details->count() <= 4){

                if (Config::getConfig('sign_for_tips')){
                    $end_srt = Config::getConfig('sign_for_tips');
                }else{
                    $end_srt = "**完**";
                }

                $l = ($all - $this->getWordsCount($end_srt) * 2) / 2;
                $content .= str_repeat(' ', $l)."<FS2>$end_srt</FS2>\n";
            }
            $data = $print->index(config('yly.machineCode'),$content,$order->id);
        }catch (\Exception $e){
            dump($e->getMessage());
            $log['msg']     = $e->getMessage();
            $log['params']  = $this->order;
            $log['content'] = $e;
            ErrorLog::create($log);
        }
    }


    protected function getWordsCount($words)
    {
        // 英文内容
        $letters = preg_replace("/[\\x80-\\xff]/","",$words);
        // 中文内容
        $chinese = preg_replace("/[^\x80-\xff]/","",$words);

        return mb_strlen($chinese) * 2 + strlen($letters);

    }

    public function failed(\Exception $exception)
    {
        dump($exception->getMessage());
        $log['msg']     = $exception->getMessage();
        $log['params']  = $this->order;
        $log['content'] = $exception;
        ErrorLog::create($log);
    }


    public function handle_back()
    {
        dd(strlen('*'),strlen(' '),strlen('A'),strlen('a'),strlen('小'),strlen(8),strlen(')'));
        $order = $this->order;
        try{
            $config = new YlyConfig(\config('yly.clientId'),\config('yly.clientSecret'));

            if (Cache::has('ylyToken')){
                $token = Cache::get('ylyToken');
            }else{
                $client = new YlyOauthClient($config);
                $token = $client->getToken();   //若是开放型应用请传授权码code
                Cache::put('ylyToken',$token,Carbon::now()->addDay());
            }

            $print = new PrintService($token->access_token, $config);

            $content = "<PW>080</PW>\n".str_repeat(' ', 14)."<FS2>**牛视界**</FS2>\n";
            $content .= str_repeat('*', 22) . "商品" . str_repeat("*", 22)."\n";
            $content .= "<table>";
            $content .= "<tr><td>商品名</td><td>规格</td><td>数量</td><td>价格</td></tr>";
            foreach ($order->details as $detail){
                if (!empty($detail->goods_alias)){
                    $name = $detail->goods_alias;
                }else{
                    $name = $detail->goods_name;
                }
                $name = $detail->goods_name;
                $spec = '';
                if (!empty($detail->spec_alias)){
                    $spec = $detail->spec_alias;
                }else if (!empty($detail->spec)){
                    $spec = $detail->spec;
                }

                $spec = $detail->spec;
                if ($detail->type_name){
                    $name .= '('.$detail->type_name.')';
                }
                $content .= sprintf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",$name,$spec,$detail->num,$detail->total_price);
            }
            $content .= "</table>";

//            $content .= "小计:￥".$order->old_price."\n";

//            $content .= "折扣:￥".($order->old_price - $order->total_price)." \n";
            $content .= str_repeat('*', 48)."\n";
            $content .= "订单总价:￥".$order->total_price." \n";

//        $content .= "<FS><center>张周兄弟烧烤</center></FS>";
            $content .= "收件人:".$order->user_name."\n";
            $content .= "联系电话:".$order->phone."\n";
            $content .= "收件地址:".$order->detail."\n";
            $content .= "订单编号:".$order->order_no."\n";
            $content .= "订单时间:". $order->pay_at . "\n";
            $content .= "牛视界客服:". Config::getConfig('phone'). "\n";

            $content .= str_repeat('.', 48)."\n";
            $content .= sprintf("<QR>custom=/v1/orders/signFor=%d</QR>",$order->id);

            if ($order->is_safe){
                $order->old_price += 1;
            }
            if ($order->details->count() <= 4){
                $content .= "<FS2><center>**完**</center></FS2>";
            }
            $data = $print->index(config('yly.machineCode'),$content,$order->id);
        }catch (\Exception $e){
            dump($e->getMessage());
            $log['msg']     = $e->getMessage();
            $log['params']  = $this->order;
            $log['content'] = $e;
            ErrorLog::create($log);
        }
    }
}
